<?php
class Cms_View_Helper_TreeNav
{
    public $view;

    public function treenav($MenuName)
    {
		$CONFIG = Zend_Registry::get('config');
		$CACHE = Zend_Registry::get('cache');
		
		if($CONFIG->application_state == 'production')
		{
			if(!$acl = $CACHE->load('acl'))
			{
				$acl = Acl::getInstance();
				$CACHE->save($acl,'acl');
			}
		}
		else
			$acl = Acl::getInstance();
		
		$auth = Zend_Auth::getInstance();
		
		if (!$auth->hasIdentity()) 
		{
			$userRole = 'guest';
		}
		else
		{
			$user = new Zend_Session_Namespace('Zend_Auth');
			$userRole = $user->userRole;
		}
		
		if($CONFIG->application_state == 'production')
		{
			if (!$menuItems = $CACHE->load("treenav_".$userRole.'_'.$MenuName))
			{
				$menu = Doctrine::getTable('Menu')->findOneByName($MenuName);
				$menuItems = $this->buildTree($menu);
				$CACHE->save($menuItems, "navigation_".$userRole.'_'.$MenuName);
			}
		}
		else
		{
			$menu = Doctrine::getTable('Menu')->findOneByName($MenuName);
			$menuItems = $this->buildTree($menu);
		}
			
		return $menuItems;
    }
	
	public function buildTree($menu)
	{
		$children = $menu->getNode()->getChildren();
	
		$menuItems = NULL;
		
		foreach($children as $child)
		{
			$Module = $child->module;
			$Controller = !empty($child->controller)?$child->controller:'index';
			$Action = !empty($child->action)?$child->action:'index';
				
			$url = '/'.$this->lcfirst($Module);
					
			if($Controller != 'index')
			{
				$url .= '/'.$this->lcfirst($Controller);
				
				if($Action != 'index')
				{
					$url .= '/'.$this->lcfirst($Action);
				}
			}
			
			$pattern = "/(.)([A-Z])/";
			$replacement = "\\1-\\2"; 
			$url = strtolower(preg_replace($pattern,$replacement,$url));
			
			if($child->alias != '')
				$url = $this->view->cmsUrl(array(),$child->module.'_'.$child->controller.'-'.$child->action);
				
			if($child->getNode()->hasChildren())
			{
				$menuItems .= '<li class="expandable">
									<div class="hitarea expandable-hitarea"></div>
									<span class="folder">'.$child->name.'</span>';
				$menuItems.= '<ul style="display: none;" class="subMenu">';
				$menuItems.= $this->buildTree($child);
				$menuItems.= '</ul></li>';
			}
			else
				$menuItems .= '<li><span class="file"><a href="'.$url.'">'.$child->name.'</a></span></li>';
			
		}
		
		return  $menuItems;
	}

    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }
	
	public function lcfirst($str) 
	{
    	return strtolower(substr($str, 0, 1)) . substr($str, 1);
	}
}
?>